
import {ElNotificationFn} from '@/utils/computedUtils'
class ErrorHandler {
  private static instance: ErrorHandler;
  private isProduction = process.env.NODE_ENV === 'production';
  private initialized = false;
  private constructor() {}
  public static getInstance(): ErrorHandler {
    if (!ErrorHandler.instance) {
      ErrorHandler.instance = new ErrorHandler();
    }
    return ErrorHandler.instance;
  }

  private handlePromiseError = (event: PromiseRejectionEvent) => {
    event.preventDefault();
    event.stopPropagation()
    const error = event.reason;
    let message = '';
    if (error?.isAxiosError) {
      if (error.response?.data?.message) {
        message = error.response.data.message;
      } else if (error.message.includes('timeout')) {
        message = '请求超时';
      } else if (error.message === 'Network Error') {
        message = '网络连接错误';
      } else if (error.response) {
        message = `请求失败(${error.response.status})`;
      }
      // ElNotificationFn('error',message);
      console.log(message,"error");
      if (!this.isProduction) {
        console.warn('[Global Error Handler] Axios Error:', {
          url: error.config?.url,
          method: error.config?.method,
          status: error.response?.status,
          message: error.message,
          data: error.response?.data
        });
      }
    }else{
      message = error.message || '操作失败'
      console.log("全局捕获错误",error)      
    }
  }
  public setupGlobalPromiseErrorHandler() {
    if (this.initialized) return;
    window.addEventListener('unhandledrejection', this.handlePromiseError);
    this.initialized = true;
    if (!this.isProduction) {
      console.log('[Global Error Handler] Initialized');
    }
  }
}
export const errorHandler = ErrorHandler.getInstance();